package com.turato.json.myjson;


import java.util.HashMap;

/**
 * @author tuhao
 * @desc json 对象，核心是Map
 */
public class JsonObject extends HashMap<String, Object> {


    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append('{');
        boolean f = false;
        for (Entry<String, Object> entry : this.entrySet()) {
            if (f) {
                sb.append(',');
            }
            sb.append(StringUtils.toJsonString(entry.getKey())).append(':').append(StringUtils.toJsonString(entry.getValue()));
            f = true;
        }
        return sb.append('}').toString();
    }


    public String toStringUnicode() {
        StringBuilder sb = new StringBuilder();
        sb.append('{');
        boolean f = false;
        for (Entry<String, Object> entry : this.entrySet()) {
            if (f) {
                sb.append(',');
            }
            sb.append(StringUtils.toUnicodeString(StringUtils.toJsonString(entry.getKey()))).append(':').append(StringUtils.toUnicodeString(StringUtils.toJsonString(entry.getValue())));
            f = true;
        }
        return sb.append('}').toString();
    }

    public <T> T get(String key, Class<T> type) {
        return type.cast(get(key));
    }

    public String getString(String key) {
        return get(key, String.class);
    }

    public JsonObject getObject(String key){
        return get(key, JsonObject.class);
    }

    public JsonArray getArray(String key){
        return get(key, JsonArray.class);
    }
}
